<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{width: 100px;height: 100px;position: absolute;background: green;}
        #box h2{height: 20px;font-size: 14px;background: #ccc;margin: 0;cursor: move}
    </style>
</head>
<body>
    <div id="box">
        <h2>标题</h2>
    </div>
</body>
<script>
    var obox = document.getElementById("box");
    var oh2 = document.querySelector("#box h2");
    // 经过了哪几个事件
    var clientW = document.documentElement.clientWidth;
    var clientH = document.documentElement.clientHeight;

    // 按下
    oh2.onmousedown = function(eve){
        // 按下时，获取事件对象，方便移动时减去按下的一瞬间，鼠标相对于事件源的坐标
        var downE = eve || window.event;
        // 移动
        document.onmousemove = function(eve){
            // 移动时，获取事件对象
            var moveE = eve || window.event;
            // 提前计算left和top，保存到变量，方便边界限定
            var l = moveE.clientX - downE.offsetX;
            var t = moveE.clientY - downE.offsetY;

            // 边界限定
            if(l < 0){
                l = 0;
            }
            if(t < 0){
                t = 0;
            }
            if(l > clientW - obox.offsetWidth){
                l = clientW - obox.offsetWidth
            }
            if(t > clientH - obox.offsetHeight){
                t = clientH - obox.offsetHeight
            }
            // 将处理之后的left和top设置给元素
            obox.style.left = l + "px";
            obox.style.top = t + "px";

            localStorage.setItem("pos",JSON.stringify({
                x:l,
                y:t
            }))

        }
        // 抬起
        document.onmouseup = function(){
            // 抬起之后，清除移动和抬起事件
            document.onmousemove = null;
            document.onmouseup = null;
        }

        // return false;
        downE.preventDefault();
    }
</script>
</html>